const loginUrl = "https://ali.ikenway.net:18443/api/auth/login";
const redirUrl = "https://ali.ikenway.net:18443/main.html";
const validateUrl = "https://ali.ikenway.net:18443/api/auth/validate"


let alert = document.getElementById("alert");
alert.hidden = true;

document.getElementById("register").onclick = function () {
    window.location.href = "/register.html";
}

function callback(res) {
    let validateData = {
        "ticket": res.ticket,
        "randStr": res.randstr
    };

    fetch(validateUrl, {
        method: 'POST',
        headers: {
            'Content-Type': "application/json"
        },
        body: JSON.stringify(validateData)
    }).then(validateRes => {
        validateRes.json().then(validateJson => {
            if (validateJson.code === 200) {
                let data = new URLSearchParams();
                data.append("username", document.getElementById("inputEmail").value);
                data.append("password", document.getElementById("inputPassword").value);

                login(data);
            } else {
                alertMsg(validateJson.msg);
            }
        })
    })
}


function login(data) {
    fetch(loginUrl, {
        method: 'POST',
        body: data
    }).then(r => {
        r.json().then(json => {
            alertMsg(json.msg);

            if (json.code === 200) {
                setTimeout(function () {
                    sessionStorage.setItem("token", json.data.token);
                    window.location.href = redirUrl;
                }, 2000);
            }
        });
    });
}
